<template>
  <div class="container">
    <div class="section">
      <ul class="info">
        <li class="list-item">
          <div class="tip">
            <span class="must">*</span>
            <span>关键词名称：</span>
          </div>
          <div class="detail">
            <el-input v-model="form.name" :maxlength="42" placeholder="请输入内容" />
          </div>
        </li>
        <li class="list-item">
          <div class="tip">
            <span class="must">*</span>
            <span>关键词类型：</span>
          </div>
          <div class="detail">
            <el-select v-model="form.type" placeholder="请选择关键词类型" clearable>
              <el-option
                v-for="item in type_arr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </li>
        <li class="list-item">
          <div class="tip">
            <span class="must">*</span>
            <span>排序：</span>
          </div>
          <div class="detail">
            <el-input-number
              v-model="form.sort"
              :precision="0"
              :step="1"
              size="medium"
              :min="0"
            />
          </div>
        </li>
        <li class="list-item">
          <div class="tip">
            <span class="must">*</span>
            <span>设置：</span>
          </div>
          <div class="detail">
            <el-button type="primary"
                       :disabled="form.type == ''" @click="chose()">关联内容
            </el-button>
          </div>
        </li>
        <li class="list-item"  :hidden="tableChoseData.length == 0">
          <div class="tip">
            <span class="must">*</span>
            <span>关联内容：</span>
          </div>
          <div class="detail">
            <!-- 表格 -->
            <div class="tableWrap">
              <!--                  <div>已选择{{projectdatalength||0}}项</div>-->
              <el-table
                @selection-change="handleSelectionChange"
                border
                :data="tableChoseData"
                :row-key="getRowKeys"
                height="550"
                style="width: 100%"
              >
                <!-- id -->
                <el-table-column fixed type="index" label="序号" width="50" />
                <el-table-column  v-for="(item, index) in tableHead" :label="item.label" :property="item.property"
                                  :key="index">
                  <template slot-scope="scope">
                    <span v-if="scope.column.property === 'groupMasterPicture' || scope.column.property === 'slaveImage' ">
                       <img :src="common.img_url+scope.row[scope.column.property]" alt class="smallBG" />
                      </span>
                    <span v-else >
                      <span v-if="scope.column.property !== 'comboType'">
                         {{scope.row[scope.column.property]}}
                      </span>
                    </span>
                    <span v-if="scope.column.property === 'comboType'">
                    <span v-if="scope.row[scope.column.property] == 0">正常购买</span>
                    <span v-if="scope.row[scope.column.property] == 1">优惠券</span>
                   </span>
                    <span v-if="scope.column.property === 'provinceName'">
                    <span v-if="scope.row[scope.column.property] == null">全国</span>
                   </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="sub-btn">
      <el-button type="primary" @click="save()">保存</el-button>
    </div>
    <!-- 关联内容 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" class="dialog"  width="1200px">
      <div class="detail project_detail" style="width: 1150px;" >
        <div class="app-container">
          <!-- form行 -->
          <div class="formDiv">
            <el-form ref="formProject" :inline="true" :model="search_form" label-width="130px" :hidden="this.form.type != 1">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="项目名称：">
                    <el-input v-model="search_form.groupProjectName" placeholder="请输入项目名称" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="项目分类：">
                      <el-select v-model="search_form.projectCategoryId" placeholder="请选择" clearable>
                        <el-option
                          v-for="item in class_arr"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="医院名称：">
                    <el-input v-model="search_form.hospitalName" placeholder="请输入医院名称" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="省份：">
                    <el-select v-model="search_form.provinceId" placeholder="请选择" clearable>
                      <el-option
                        v-for="item in addressOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-form-item label="">
                    <el-button type="primary medium" @click="search()">搜索</el-button>
                </el-form-item>
              </el-row>
            </el-form>
            <el-form ref="formGoods" :inline="true" :model="search_form" label-width="130px" :hidden="this.form.type == 1">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="礼包名称：">
                    <el-input v-model="search_form.name" placeholder="请输入礼包名称" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="礼包内容：">
                    <el-select v-model="search_form.comboType" placeholder="请选择" clearable>
                      <el-option
                        v-for="item in comboType_arr"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select >
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="省份：">
                    <el-select v-model="search_form.provinceId" placeholder="请选择" clearable>
                      <el-option
                        v-for="item in addressOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-form-item label="">
                  <el-button type="primary medium" @click="search()">搜索</el-button>
                </el-form-item>
              </el-row>
            </el-form>
          </div>
          <!-- 表格 -->
          <div class="tableWrap">
            <!--                  <div>已选择{{projectdatalength||0}}项</div>-->
            <el-table
              @selection-change="handleSelectionChange"
              v-loading="table_loading"
              ref="tableData"
              :data="tableData"
              :row-key="getRowKeys"
              height="250"
              style="width: 100%"
            >
              <!-- id -->
              <el-table-column type="selection" width="55" :reserve-selection="true" />
              <el-table-column fixed type="index" label="序号" width="50" />
              <el-table-column  v-for="(item, index) in tableHead" :label="item.label" :property="item.property"
                       :key="index">
                <template slot-scope="scope">

                    <span v-if="scope.column.property === 'groupMasterPicture' || scope.column.property === 'slaveImage' ">
                       <img :src="common.img_url+scope.row[scope.column.property]" alt class="smallBG" />
                      </span>
                    <span v-else >
                      <span v-if="scope.column.property !== 'comboType'">
                         {{scope.row[scope.column.property]}}
                      </span>
                    </span>
                  <span v-if="scope.column.property === 'comboType'">
                    <span v-if="scope.row[scope.column.property] == 0">正常购买</span>
                    <span v-if="scope.row[scope.column.property] == 1">优惠券</span>
                   </span>
                    <span v-if="scope.column.property === 'provinceName'">
                    <span v-if="scope.row[scope.column.property] == null">全国</span>
                   </span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页器 -->
          <div class="block">
            <el-pagination
              background
              :page-sizes="[10,20,50,100]"
              :page-size="search_form.pageSize"
              :pager-count="11"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @current-change="change_page"
              @size-change="handleSizeChange"
            />
          </div>
          <div class="sub">
            <el-button type="primary" :disabled="tableChoseData.length == 0 " @click="submit_chose()">保存</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { projectList } from '../../../api/project'
  import { getGoodsList } from '../../../api/goods'
  import { provinceList } from '../../../api/province'
  import { getCateDownList } from '../../../api/category'
  import { addIndex, updateIndex } from '../../../api/drop'
  import { addKeyWord, keyWordDetail, updateKeyWord } from '../../../api/keyWord'
  export default {
    data(){
      return{
        exampleProject:[
          {
            label:'排序',
            property:'sort'
          },{
            label:'项目名称',
            property:'groupProjectName'
          },{
            label:'项目分类',
            property:'projectCategoryName'
          },{
            label:'项目图片',
            property:'groupMasterPicture'
          },{
            label:'省份',
            property:'provinceName'
          },{
            label:'医院名称',
            property:'hospitalName'
          },{
            label:'价格类型',
            property:'payTypeName'
          },{
            label:'原价',
            property:'price'
          },{
            label:'拼团价',
            property:'groupPrice'
          },{
            label:'原价定金',
            property:'subscription'
          },{
            label:'拼团定金',
            property:'groupSubscription'
          }
        ],
        exampleGoods:[
          {
            label:'排序',
            property:'sortWidget'
          }, {
            label: '套餐名称',
            property: 'name'
          },{
            label:'套餐图片',
            property:'slaveImage'
          },{
            label:'礼包地区',
            property:'provinceName'
          },{
            label:'礼包内容',
            property:'comboType'
          },{
            label:'展示价',
            property:'price'
          },{
            label:'售价',
            property:'yprice'
          }
        ],
        page_status:'',
        dialogVisible:false,
        title:'',
        addressOptions:[],//省份
        class_arr: [],//分类
        comboType_arr: [
          { value: 0, label: "正常购买" },
          { value: 1, label: "优惠券" },
        ], //
        type_arr: [
          { value: 1, label: "项目" },
          { value: 2, label: "礼包" },
        ],
        form:{
          keyword_id:undefined,
          name:'',
          type:'',//	关键词类型：1项目2礼包
          sort:1,
          general_ids:'',//	用id：type=1 是 project_id ，type=2 是 group_vip_combo_id	是
        },
        search_form:{
          groupProjectName: undefined,  //   项目名称
          projectCategoryId: undefined, //   分类
          hospitalName: undefined, //   医院名称
          provinceId: undefined,//   省份
          comboType:undefined,//礼包内容
          name: undefined,//礼包内容
          pageNum: 1,
          pageSize: 10,
          status:"",
        },
        tableChoseData:[],
        table_loading:false,
        tableData:[],
        total:0,
        tableHead:this.exampleProject,
      }
    },
    mounted() {
      //page_status  1 添加  2 编辑
      this.page_status = this.$route.query.page_status
      this.form.id = this.$route.query.id
      switch (this.page_status) {
        case 1:
          this.$route.meta.title = "添加关键词";
          break;
        case 2:
          this.$route.meta.title = "编辑关键词";
          break;
        default:
          break;
      }
      if(this.form.id){
        this.detail(this.form.id)
      }

    },
    methods:{
      // 序号
      table_index(index) {
        return (this.search_form.page - 1) * this.search_form.pageSize + index + 1;
      },

      getRowKeys(row) {
        return row.id;
      },

      //选择弹窗
      chose(){
        this.title = this.form.type == 1 ?"关联项目" : "关联礼包"
        this.tableHead = this.form.type == 1 ? this.exampleProject : this.exampleGoods
        this.dialogVisible = true
        if(this.form.type == 1 ){
          this.search()
          this.get_catelist()
        }else {
          this.search()
        }
        this.get_province()
      },

      ///选择确认
      submit_chose(){
        this.onsubmitPro()
      },

      //确定勾选项目数据
      onsubmitPro() {
        const selectData = this.$refs.tableData.selection;
        let ids = [];
        selectData.forEach((e) => {
          ids.push(e.id);
        });
        ids = ids.join(","); //分割
        ids = ids.toString(); // 拍平成字符串
        this.form.general_ids = ids;
        this.tableChoseData = selectData
        this.dialogVisible = false
      },


      //获取项目列表
      get_project_list() {
        this.table_loading = true;
        projectList({
          groupProjectName :this.search_form.groupProjectName == undefined ? '': this.search_form.groupProjectName,
          projectCategoryId : this.search_form.projectCategoryId == undefined ? '': this.search_form.projectCategoryId+ "",
          hospitalName : this.search_form.hospitalName == undefined ? '': this.search_form.hospitalName,
          provinceId :this.search_form.provinceId == undefined ? '': this.search_form.provinceId+ "",
          status :"",
          pageNum: this.search_form.pageNum,
          pageSize: this.search_form.pageSize,
        })
          .then((result) => {
            const res = result.data;
            if (res.code === 0) {
              res.data.list.forEach((item) => {
                item.status = item.status - 0;
              });
              this.tableData = res.data.list;
              if (this.form.general_ids.length > 0) {
                for (var i = 0; i <this.form.general_ids.length; i++) {
                  for (var j = 0; j < this.tableData.length; j++) {
                    if (this.form.general_ids[i] - 0 == this.tableData[j].id) {
                      //里面包含有的都回显打勾 //回显打勾核心，toggleRowSelection的第一个参数是需要打勾的那一行数据，第二个参数表示是否选中，传true this.items[j],
                      this.$refs.tableData.toggleRowSelection(
                        this.tableData[j],
                        true
                      );
                    }
                  }
                }
              }
              this.total = res.data.count;
              this.table_loading = false;
            }
          })
          .catch((err) => {
            this.table_loading = false;
            //   this.$message.error('服务器网络错误，请稍后重试');
            this.$message.error(err);
          });
      },

      //获取礼包列表
      get_goods_list() {
        this.table_loading = true;
        getGoodsList({
          name : this.search_form.name == undefined ? '': this.search_form.name,
          provinceId : (this.search_form.provinceId == undefined || this.search_form.provinceId == '') ? undefined : this.search_form.provinceId+ "",
          comboType: this.search_form.comboType === "" ? null : this.search_form.comboType,
          status : null,
          pageNum: this.search_form.pageNum,
          pageSize: this.search_form.pageSize,
        })
          .then((res) => {
            this.total = res.data.data.count;
            this.search_form.pageNum = res.data.data.pageNum;
            this.search_form.pageSize = res.data.data.pageSize;
            this.tableData = res.data.data.list;
            this.table_loading = false;
          })
          .catch((error) => {
            this.table_loading = false;
            this.$message.error("网络连接错误，请稍后再试");
          });
      },

      //获取省份
      get_province(){
        provinceList({}).then(res => {
          this.addressOptions = res.data.data.list // 将获取的省份option 赋值 addressOptions
        }).catch(res => {
          this.$message.error('网络连接错误，请稍后再试')
        })
      },

      // 获取分类列表
      get_catelist() {
        getCateDownList({
          pageNum: 1,
          pageSize: 1000,
        })
          .then((result) => {
            const res = result.data;
            if (res.code === 0) {
              const arr = [];
              res.data.list.forEach((item) => {
                arr.push({
                  value: item.id,
                  label: item.categoryName,
                });
              });
              this.class_arr = arr;
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      },

      //筛选
      search(){
        if(this.form.type == 1){
            this.get_project_list()
        }else {
          this.get_goods_list()
        }
      },

      //获取详情
      detail(id){
        keyWordDetail({
          keyword_id:id
        }).then((result) => {
          if(result.data.status == 0){
            let item = result.data.data
            this.tableHead = item.type == 1 ? this.exampleProject : this.exampleGoods
            this.tableChoseData = item.relation_data


            this.form.keyword_id = item.id
            this.form.name =item.name
            this.form.type =item.type
            this.form.sort =item.sort
            let idList = [];
            idList = item.relation_general_ids.split(",");
            this.$set(this.form,"general_ids",idList);
          }
        })
          .catch((err) => {
            this.$message.error("服务器网络错误，请稍后重试");
          });
      },

      //保存
      save(){
        if (this.form.name === "") {
          this.$message.error("请输入关键词名称");
        } else if (this.form.type === "") {
          this.$message.error("请选择关键词类型");
        }else if (this.form.general_ids === "") {
          this.$message.error("请设置关联内容");
        }else {
          switch (+this.page_status) {
            case 1:
              this.add_keyWord(this.form);
              break;
            case 2:
              this.rewrite_keyWord(this.form);
              break;

            default:
              break;
          }
        }
      },

      //添加
      add_keyWord(opt){
        addKeyWord(opt) .then((res) => {
          if(res.data.status == 0){
            this.$message({
              showClose: true,
              message: "添加成功" ,
              type: "success",
            });
            this.$router.push({ path: '/keywordMange'})
          }else {
            this.$message.error(res.data.message);
          }
        })
          .catch((res) => {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error",
            });
          });

      },

      //编辑
      rewrite_keyWord(opt){
        updateKeyWord(opt) .then((res) => {
          if(res.data.status == 0){
            this.$message({
              showClose: true,
              message: "编辑成功" ,
              type: "success",
            });
            this.$router.push({ path: '/keywordMange'})
          }else {
            this.$message.error("编辑失败" ,res.data.message);
          }
        })
          .catch((res) => {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error",
            });
          });
      },

      //表格选择
      handleSelectionChange(val) {
        if (val) {
          this.tableChoseData = val
        }
      },
      //
      change_page(page){
        this.search_form.pageNum = page;
        this.search();
      },
      //
      handleSizeChange(page){
        this.search_form.pageSize= page;
        this.search();
      },
    },
  }
</script>
<style lang="scss" scoped>
  .container {
    padding: 30px;
    .section {
      .title {
        width: 130px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        margin-bottom: 20px;
      }
      .info {
        margin-left: 40px;
        .list-item {
          margin-bottom: 20px;
          .tip {
            font-size: 14px;
            display: inline-block;
            vertical-align: middle;
            width: 150px;
            text-align: right;
            .msk {
              font-size: 10px;
              color: #666;
              margin-right: 20px;
              margin-top: 10px;
            }
            .must {
              display: inline-block;
              vertical-align: middle;
              color: #ff3040;
            }
          }
          .detail {
            color: #666;
            min-width: 350px;
            font-size: 16px;
            display: inline-block;
            vertical-align: top;
            .el-select {
              display: block !important;
            }
            &.project_detail {
              vertical-align: top;
            }

            .rule {
              display: flex;
              align-items: center;
              justify-content: space-around;
              flex-direction: row;
            }
          }
        }
      }
    }
    .sub-btn {
      .el-button {
        margin: 80px auto 10px auto;
        display: block;
      }
    }

    .form-control {
      width: 100%;
      padding-right: 6px;
      min-height: 300px;
      -webkit-overflow-scrolling: touch;
      resize: none;
      outline: 0 none;
      margin-top: 12px;
      font-size: 14px;
      /*font-family: MicrosoftYaHei;*/
      color: rgba(13, 20, 30, 1);
      line-height: 19px;
      opacity: 0.6;
    }

    .block{
      margin-top: 20px;
    }
    .sub {
      .el-button {
        margin: 20px auto 0 auto;
        display: block;
      }
    }

    .dialog {
      margin-bottom: 20px;
    }

    .smallBG {
      width: 40px;
      height: 40px;
    }

  }
</style>
